<template>
  <nav class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex items-center justify-between h-16">
        <!-- Logo和应用名称 -->
        <div class="flex items-center space-x-8">
          <router-link
            to="/"
            class="flex items-center space-x-2 text-xl font-bold text-gray-900 hover:text-blue-600 transition-colors"
          >
            <PenTool class="w-8 h-8 text-blue-500" />
            <span class="hidden sm:inline">AI作文批改</span>
          </router-link>
          
          <!-- 桌面端导航链接 -->
          <div class="hidden md:flex items-center space-x-1">
            <router-link
              v-for="link in navLinks"
              :key="link.path"
              :to="link.path"
              class="px-4 py-2 text-sm font-medium rounded-lg transition-colors"
              :class="[
                isActive(link.path)
                  ? 'bg-blue-100 text-blue-600'
                  : 'text-gray-700 hover:bg-gray-100 hover:text-gray-900'
              ]"
            >
              <div class="flex items-center space-x-2">
                <component :is="link.icon" class="w-4 h-4" />
                <span>{{ link.label }}</span>
              </div>
            </router-link>
          </div>
        </div>
        
        <!-- 右侧：用户菜单/登录按钮 -->
        <div class="flex items-center space-x-4">
          <!-- 未登录状态 -->
          <template v-if="!isAuthenticated">
            <router-link
              to="/login"
              class="hidden sm:inline-flex px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"
            >
              登录
            </router-link>
            <router-link
              to="/register"
              class="hidden sm:inline-flex px-4 py-2 text-sm font-medium bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
            >
              注册
            </router-link>
          </template>
          
          <!-- 已登录状态 -->
          <template v-else>
            <!-- 用户菜单 -->
            <div class="hidden md:block relative" ref="userMenuRef">
              <button
                @click="toggleUserMenu"
                class="flex items-center space-x-2 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <div class="w-8 h-8 bg-blue-500 text-white rounded-full flex items-center justify-center">
                  {{ userInitial }}
                </div>
                <span class="hidden lg:inline">{{ userName }}</span>
                <ChevronDown class="w-4 h-4" :class="{ 'transform rotate-180': showUserMenu }" />
              </button>
              
              <!-- 下拉菜单 -->
              <transition
                enter-active-class="transition ease-out duration-100"
                enter-from-class="transform opacity-0 scale-95"
                enter-to-class="transform opacity-100 scale-100"
                leave-active-class="transition ease-in duration-75"
                leave-from-class="transform opacity-100 scale-100"
                leave-to-class="transform opacity-0 scale-95"
              >
                <div
                  v-if="showUserMenu"
                  class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1"
                >
                  <router-link
                    to="/profile"
                    @click="showUserMenu = false"
                    class="flex items-center space-x-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors"
                  >
                    <User class="w-4 h-4" />
                    <span>个人中心</span>
                  </router-link>
                  
                  <router-link
                    to="/history"
                    @click="showUserMenu = false"
                    class="flex items-center space-x-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors"
                  >
                    <FileText class="w-4 h-4" />
                    <span>我的作文</span>
                  </router-link>
                  
                  <div class="border-t border-gray-200 my-1"></div>
                  
                  <button
                    @click="handleLogout"
                    class="w-full flex items-center space-x-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors"
                  >
                    <LogOut class="w-4 h-4" />
                    <span>退出登录</span>
                  </button>
                </div>
              </transition>
            </div>
          </template>
          
          <!-- 移动端汉堡菜单按钮 -->
          <button
            @click="toggleMobileMenu"
            class="md:hidden p-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <component :is="showMobileMenu ? X : Menu" class="w-6 h-6" />
          </button>
        </div>
      </div>
    </div>
    
    <!-- 移动端菜单 -->
    <transition
      enter-active-class="transition ease-out duration-100"
      enter-from-class="transform opacity-0 -translate-y-2"
      enter-to-class="transform opacity-100 translate-y-0"
      leave-active-class="transition ease-in duration-75"
      leave-from-class="transform opacity-100 translate-y-0"
      leave-to-class="transform opacity-0 -translate-y-2"
    >
      <div
        v-if="showMobileMenu"
        class="md:hidden border-t border-gray-200 bg-white"
      >
        <div class="px-2 pt-2 pb-3 space-y-1">
          <!-- 未登录：显示登录/注册 -->
          <template v-if="!isAuthenticated">
            <router-link
              to="/login"
              @click="showMobileMenu = false"
              class="block px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            >
              登录
            </router-link>
            <router-link
              to="/register"
              @click="showMobileMenu = false"
              class="block px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            >
              注册
            </router-link>
          </template>
          
          <!-- 已登录：显示导航链接 -->
          <template v-else>
            <router-link
              v-for="link in navLinks"
              :key="link.path"
              :to="link.path"
              @click="showMobileMenu = false"
              class="flex items-center space-x-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors"
              :class="[
                isActive(link.path)
                  ? 'bg-blue-100 text-blue-600'
                  : 'text-gray-700 hover:bg-gray-100'
              ]"
            >
              <component :is="link.icon" class="w-4 h-4" />
              <span>{{ link.label }}</span>
            </router-link>
            
            <div class="border-t border-gray-200 my-2"></div>
            
            <router-link
              to="/profile"
              @click="showMobileMenu = false"
              class="flex items-center space-x-2 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <User class="w-4 h-4" />
              <span>个人中心</span>
            </router-link>
            
            <button
              @click="handleLogout"
              class="w-full flex items-center space-x-2 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 rounded-lg transition-colors"
            >
              <LogOut class="w-4 h-4" />
              <span>退出登录</span>
            </button>
          </template>
        </div>
      </div>
    </transition>
  </nav>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  PenTool, 
  Menu, 
  X, 
  ChevronDown, 
  User, 
  LogOut,
  FileText,
  PlusCircle,
  History
} from 'lucide-vue-next';
import { useUserStore } from '../stores/user.js';

/**
 * NavigationBar 组件
 * 应用顶部导航栏，包含Logo、导航链接、用户菜单和移动端汉堡菜单
 */

// ==================== Composition API ====================
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// ==================== Refs ====================
const showMobileMenu = ref(false);
const showUserMenu = ref(false);
const userMenuRef = ref(null);

// ==================== Computed ====================

/**
 * 是否已登录
 */
const isAuthenticated = computed(() => userStore.isAuthenticated);

/**
 * 用户名
 */
const userName = computed(() => userStore.user?.username || '用户');

/**
 * 用户名首字母
 */
const userInitial = computed(() => {
  return userName.value.charAt(0).toUpperCase();
});

/**
 * 导航链接（需要登录）
 */
const navLinks = computed(() => {
  if (!isAuthenticated.value) return [];
  
  return [
    {
      path: '/submit',
      label: '提交作文',
      icon: PlusCircle,
    },
    {
      path: '/history',
      label: '历史记录',
      icon: History,
    },
  ];
});

// ==================== Methods ====================

/**
 * 判断路由是否激活
 */
const isActive = (path) => {
  return route.path === path || route.path.startsWith(path + '/');
};

/**
 * 切换移动端菜单
 */
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value;
  showUserMenu.value = false; // 关闭用户菜单
};

/**
 * 切换用户菜单
 */
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value;
};

/**
 * 处理退出登录
 */
const handleLogout = async () => {
  try {
    await userStore.logout();
    showUserMenu.value = false;
    showMobileMenu.value = false;
    router.push('/');
  } catch (error) {
    console.error('[NavigationBar] Logout failed:', error);
    alert('退出登录失败');
  }
};

/**
 * 点击外部关闭菜单
 */
const handleClickOutside = (event) => {
  if (userMenuRef.value && !userMenuRef.value.contains(event.target)) {
    showUserMenu.value = false;
  }
};

// ==================== Lifecycle ====================

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
/* 确保下拉菜单不被遮挡 */
.relative {
  position: relative;
}

/* 平滑过渡 */
.transition {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
</style>

